package com.ricchieri.manage.bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.util.FacesUtil;

@ManagedBean(name = "loginUserMB")
@ViewScoped
public class LoginUserManageBean extends GenericManageBean {

	private static final long serialVersionUID = -4192116597583059647L;
	private String username;
	private String password;
	
	@ManagedProperty(value = "#{customAuthenticationManager}")
	CustomAuthenticationManager manager;
	
	public String login() {
		
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
		
		try {
			Authentication authenticate = manager.authenticate(token);
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(authenticate);
				return BusinessSettings.SUCCESS;
			}
		} catch (BadCredentialsException exception) {
			FacesUtil.showErrorMessage("loginForm", exception.getMessage());
			
			return BusinessSettings.UNSUCCESS;
		}
		
		return BusinessSettings.UNSUCCESS;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public CustomAuthenticationManager getManager() {
		return manager;
	}

	public void setManager(CustomAuthenticationManager manager) {
		this.manager = manager;
	}
}
